package com.example.xViewChat.NettyClient;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import io.ganguo.chat.core.protocol.Constant;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
 * Created by hasee on 2016-03-31.
 */
public class EventListenerManager {
    public static ArrayList<EventListener> getListeners() {
        return listeners;
    }

    private static ArrayList<EventListener> listeners = new ArrayList<EventListener>();

    public static void registerListener(EventListener listener, Context context) {
        if (!listeners.contains(listener)) {
            listeners.add(listener);
            Collections.sort(listeners, new MessageReceiveComparator(context));
        }
    }

    public static void removeListener(EventListener listener) {
        for (int i = 0; i < listeners.size(); i++) {
            if (listener.getClass() == listeners.get(i).getClass()) {
                listeners.remove(i);
            }
        }
    }

    private static class MessageReceiveComparator implements Comparator<EventListener> {

        Context mContext;

        public MessageReceiveComparator(Context context) {
            this.mContext = context;
        }


        @Override
        public int compare(EventListener arg1, EventListener arg2) {
            Integer order1 = Constant.CIM_DEFAULT_MESSAGE_ORDER;
            Integer order2 = Constant.CIM_DEFAULT_MESSAGE_ORDER;
            ActivityInfo info;
            if (arg1 instanceof Activity) {

                try {
                    info = mContext.getPackageManager().getActivityInfo(((Activity) (arg1)).getComponentName(), PackageManager.GET_META_DATA);
                    if (info.metaData != null) {
                        order1 = info.metaData.getInt("CIM_RECEIVE_ORDER");
                    }

                } catch (Exception e) {
                }
            }

            if (arg1 instanceof Activity) {
                try {
                    info = mContext.getPackageManager().getActivityInfo(((Activity) (arg2)).getComponentName(), PackageManager.GET_META_DATA);
                    if (info.metaData != null) {
                        order2 = info.metaData.getInt("CIM_RECEIVE_ORDER");
                    }

                } catch (Exception e) {
                }
            }

            return order2.compareTo(order1);
        }
    }
}
